import { ref, Ref, watch } from 'vue';

const calculateWinner = (squares: (string|null)[]):string|null => {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
};

export type Squares = (string | null)[]

export const DefaultSquares = Array<string | null>(9).fill(null);

export default function useWinner(squares: Ref<Squares>) {
  const winner = ref<string|null>(null);

  const calc = () => {
    winner.value = calculateWinner(squares.value);
  };
  watch(squares, calc, { deep: true });

  return {
    winner,
  };
}
